package moni.anyou.com.view.amap;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;

import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import moni.anyou.com.view.config.AnyouerApplication;
import moni.anyou.com.view.utils.AppcationUtils;


public class LocationService {




    public AMapLocationClient locationClient;
    public AMapLocationClientOption locationOption;
    public LocationListen locationListen;

    public Boolean isLocationOne=false;

    public interface LocationListen{
        public void onListen(AMapLocation location,String result);
    }



    public long httpTimeOut=15000;
    public long interval=15*1000;


    private AMapLocationListener locationListener = (AMapLocationListener)(new AMapLocationListener() {
        public final void onLocationChanged(AMapLocation location) {

            Log.d("test","location="+location);

            if (location != null) {
                StringBuffer sb = new StringBuffer();
                if (location.getErrorCode() == 0) {



                    sb.append("定位成功\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");
                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    sb.append("兴趣点    : " + location.getPoiName() + "\n");
                    LocationService.LocationListen option = LocationService.this.getLocationListen();
                    if (option != null) {
                        option.onListen(location,sb.toString());
                    }
                    if(isLocationOne)
                    {
                        stopLocation();
                        destroyLocation();
                    }

                    Log.d("test", sb.toString());
                } else {
                    sb.append("定位失败\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                }

                sb.append("***定位质量报告***").append("\n");
                sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble()?"开启":"关闭").append("\n");
                sb.append("* GPS状态：").append(getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
                sb.append("* GPS星数：").append(getGPSStatusString(location.getLocationQualityReport().getGPSSatellites())).append("\n");
                sb.append("* 网络类型：" + location.getLocationQualityReport().getNetworkType()).append("\n");
                sb.append("* 网络耗时：" + location.getLocationQualityReport().getNetUseTime()).append("\n");
                sb.append("****************").append("\n");
                //定位之后的回调时间
                //				sb.append("回调时间: " + Utils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");

                //解析定位结果，
                String result = sb.toString();
                //Log.d("test",result);
               // Toast.makeText(AnyouerApplication.getAppContext(),result,Toast.LENGTH_LONG).show();
            }

        }
    });

    @Nullable
    public final LocationService.LocationListen getLocationListen() {
        return this.locationListen;
    }

    public final void setLocationListen(@Nullable LocationService.LocationListen var1) {
        this.locationListen = var1;
    }

    private final void initLocation() {
        locationClient = new AMapLocationClient(AppcationUtils.getInstance());
        locationOption = this.getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);

    }

    private final AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mOption.setGpsFirst(true);
        mOption.setHttpTimeOut(this.httpTimeOut);
        if(isLocationOne)
        {
            mOption.setInterval(200);
        }else {
            mOption.setInterval(this.interval);
        }
        mOption.setNeedAddress(true);
        mOption.setOnceLocation(false);
        mOption.setOnceLocationLatest(false);
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);
        mOption.setSensorEnable(false);
        mOption.setWifiScan(true);
        mOption.setLocationCacheEnable(true);
        mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);

        return mOption;
    }



    private final String getGPSStatusString(int statusCode) {
        String str = "";
        switch(statusCode) {
            case 0:
                str = "GPS状态正常";
                break;
            case 1:
                str = "手机中没有GPS Provider，无法进行GPS定位";
                break;
            case 2:
                str = "GPS关闭，建议开启GPS，提高定位质量";
                break;
            case 3:
                str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
                break;
            case 4:
                str = "没有GPS定位权限，建议开启gps定位权限";
        }

        return str;
    }

    private final void resetOption() {
        AMapLocationClientOption option = this.locationOption;
        

        option.setGpsFirst(true);
        option = this.locationOption;
        option.setLocationCacheEnable(false);
        option = this.locationOption;
       
        option.setOnceLocation(false);
        option = this.locationOption;
     

        option.setOnceLocationLatest(false);
        option = this.locationOption;
        

        option.setSensorEnable(false);
        option = this.locationOption;
        

        option.setInterval(this.interval);
        option = this.locationOption;


        option.setHttpTimeOut(this.httpTimeOut);
    }

    public final void startLocation() {
        this.resetOption();
        AMapLocationClient option = this.locationClient;


        AMapLocationClientOption var10001 = this.locationOption;

        option.setLocationOption(var10001);
        option = this.locationClient;


        option.startLocation();
    }

    public final void stopLocation() {
        AMapLocationClient option = this.locationClient;

        option.stopLocation();


    }

    public final void destroyLocation() {
        AMapLocationClient option = this.locationClient;

        if (option != null) {
            option = this.locationClient;

            option.onDestroy();
        }

    }

    public LocationService() {
        this.initLocation();
    }

    public LocationService(boolean isLocationOne) {
        this.isLocationOne=isLocationOne;
        this.initLocation();
    }


    public  boolean isLocationEnabled(Activity context) {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode =
                        Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders =
                    Settings.Secure.getString(
                            context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }

    public boolean showLocationEnabled(Activity context) {
        if (isLocationEnabled(context)) {
            return true;
        }
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        context.startActivityForResult(intent, 1315);
        Toast.makeText(context,"需要开启位置定位",Toast.LENGTH_LONG).show();
        return false;
    }

    public  void checkRxPermissions(Activity context){
        RxPermissions rxPermissions = new RxPermissions(context);
        String[] arr = {
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
//                      Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS
        };
        rxPermissions.requestEach(arr).buffer(arr.length)
                .subscribe(new Observer<List<Permission>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(List<Permission> list) {

                        boolean b=true;
                        for(Permission it :list ){
                            if(it.granted==false){
                                b=false;
                                break;
                            }
                        }
                        if(b)
                        {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


}
